package com.dup.jxlh.admin.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.dup.jxlh.admin.entities.auth.AuthUser;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import java.math.BigInteger;
import java.time.LocalDateTime;

@Component
public class AppMetaObjectHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        AuthUser authUser = getAuthUser();
        this.strictInsertFill(metaObject, "createdAt", LocalDateTime.class, LocalDateTime.now());
        this.strictInsertFill(metaObject, "recordId", BigInteger.class, authUser.getId());
        this.strictInsertFill(metaObject, "companyId", BigInteger.class, authUser.getCompanyId());
        this.strictInsertFill(metaObject, "departmentId", BigInteger.class, authUser.getDepartmentId());

        this.strictUpdateFill(metaObject, "updatedAt", LocalDateTime.class, LocalDateTime.now());
        this.strictUpdateFill(metaObject, "operateId", BigInteger.class, authUser.getId());
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        AuthUser authUser = getAuthUser();
        this.strictUpdateFill(metaObject, "updatedAt", LocalDateTime.class, LocalDateTime.now());
        this.strictUpdateFill(metaObject, "operateId", BigInteger.class, authUser.getId());
    }

    private AuthUser getAuthUser(){
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        return (AuthUser) auth.getPrincipal();
    }

}
